#!python3
import os
import time
import numpy as np
import img_preprocess as pre
import knn_recog as recog


IMG = 'pic.png'
IMG_SIZE = (32, 32)
CHECK_INTERVAL = 1  # second(s)


def recog_digit(filename=IMG):
    imgs = pre.pre_process(filename)
    digits = []
    for im in imgs:
        arr = pre.get_array(im)
        digit = recog.predict(arr)[0]
        digit = int(digit)
        digits.append(digit)

    return arr, digits


def print_result(arr, digit):
    """改进为多数字识别后，此函数弃用"""
    CHAR = ' .'  # Place Holder
    arr = arr.reshape(IMG_SIZE)
    for y in range(IMG_SIZE[1]):
        for x in range(IMG_SIZE[0]):
            if arr[y][x] == 1:
                print(' %i' % digit, end='')
            else:
                print(CHAR, end='')
        print()


if __name__ == '__main__':
    total = 0
    last_modified_time = os.path.getmtime(IMG)
    while True:
        time.sleep(CHECK_INTERVAL)
        if os.path.getmtime(IMG) > last_modified_time:
            # the picture file has changed
            last_modified_time = os.path.getmtime(IMG)
            arr, digits = recog_digit()
            # print_result(arr, digit)
            print(digits)

            total += 1
            print('total: %i' % total)
